<?php
namespace Util\CloudPrint;

use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Factory;

class YiLianYun
{
    /**
     * 请求域名
     */
    private $apiUrl = 'https://open-api.10ss.net/';

    /**
     * 开发者的应用ID
     */
    private $client_id;

    /**
     * 开发者的应用密钥
     */
    private $client_secret;

    /**
     * 授权的token
     */
    private $access_token;

    /**
     * access_token redis key
     */
    private $yilianyun_accessTokenKey = 'yilianyun_accessToken';

    /**
     * Feie constructor.
     * @param string $client_id
     * @param string $access_token
     */
    public function __construct($client_id = '', $client_secret= '')
    {
        $this->client_id = $client_id;
        $this->client_secret = $client_secret;
        $this->access_token = Factory::cache('default')->get($this->yilianyun_accessTokenKey.'::'.$this->client_id);
    }

    /**
     * 易联云授权
     * 官网文档地址:http://doc2.10ss.net/371770
     */
    public function oauth()
    {
        $params = [
            'client_id'     => $this->client_id,
            'grant_type'    => 'client_credentials',
            'scope'         => 'all',
            'id'            => uuid(),
            'timestamp'     => time(),
            'sign'          => strtolower(md5($this->client_id.'+'.time().'+'.$this->client_secret)),
        ];

        $apiUrl = $this->apiUrl.'oauth/oauth';
        $reponse = request($apiUrl, $params);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['error']) && $reponseData['error'] != 0){
                return ResultWrapper::fail($reponseData['error_description'],$reponseData['error']);
            }

            Factory::cache('default')->set($this->yilianyun_accessTokenKey.'::'.$this->client_id, $reponseData['body']['access_token']);
            return ResultWrapper::success($reponseData['body']);
        }
    }

    /**
     * 文本打印
     * 官网文档地址: http://doc2.10ss.net/372519
     * @params string $machine_code 易联云打印机终端号
     * @params string $origin_id    商户系统内部订单号
     * @params string $content      打印内容
     */
    public function print($machine_code, $origin_id, $content)
    {
        if(empty($this->access_token)){
            $result = self::oauth();
            if(!$result->isSuccess()){
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
        }

        $params = [
            'client_id'     => $this->client_id,
            'access_token'  => $this->access_token,
            'machine_code'  => $machine_code,
            'origin_id'     => $origin_id,
            'id'            => uuid(),
            'timestamp'     => time(),
            'sign'          => strtolower(md5($this->client_id.'+'.time().'+'.$this->client_secret)),
            'content'       => $content,
        ];

        $apiUrl = $this->apiUrl.'print/index';
        $reponse = request($apiUrl, $params);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['error']) && $reponseData['error'] != 0){
                return ResultWrapper::fail($reponseData['error_description'],$reponseData['error']);
            }
            return ResultWrapper::success($reponseData['body']);
        }
    }

    /**
     * 声音调节接口
     * 官网文档地址 http://doc2.10ss.net/372523
     */
    public function setsound($machine_code, $response_type, $voice)
    {
        if(empty($this->access_token)){
            $result = self::oauth();
            if(!$result->isSuccess()){
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
        }

        $params = [
            'client_id'     => $this->client_id,
            'access_token'  => $this->access_token,
            'machine_code'  => $machine_code,
            'response_type' => $response_type,
            'voice'         => $voice,
            'timestamp'     => time(),
            'sign'          => strtolower(md5($this->client_id.'+'.time().'+'.$this->client_secret)),
            'id'            => uuid(),
        ];

        $apiUrl = $this->apiUrl.'printer/setsound';
        $reponse = request($apiUrl, $params);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['error']) && $reponseData['error'] != 0){
                return ResultWrapper::fail($reponseData['error_description'],$reponseData['error']);
            }
            return ResultWrapper::success($reponseData['body']);
        }
    }

    /**
     *  取消所有未打印订单
     *  官网文档地址 http://doc2.10ss.net/372526
     */
    public function cancelall($machine_code)
    {
        if(empty($this->access_token)){
            $result = self::oauth();
            if(!$result->isSuccess()){
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
        }

        $params = [
            'client_id'     => $this->client_id,
            'access_token'  => $this->access_token,
            'machine_code'  => $machine_code,
            'timestamp'     => time(),
            'sign'          => strtolower(md5($this->client_id.'+'.time().'+'.$this->client_secret)),
            'id'            => uuid(),
        ];

        $apiUrl = $this->apiUrl.'printer/cancelall';
        $reponse = request($apiUrl, $params);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['error']) && $reponseData['error'] != 0){
                return ResultWrapper::fail($reponseData['error_description'],$reponseData['error']);
            }
            return ResultWrapper::success($reponseData['body']);
        }
    }
}